package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.HashMap;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    //发送短信
    @Override
    public void sendMsg(String phone) {
        //生成几位随机数
        String code = RandomUtil.randomNumbers(6);
        code="1234"; //先写死
        //调用阿里云sms发短信
        // smsTemplate.sendSms(phone,code); //todo 开发期间注释 省的花短信费
        //将短信存入redis(5分钟)
        redisTemplate.opsForValue().set("code:"+phone,code, Duration.ofSeconds(300)); //使用秒数当成5分钟
    }

    //登录注册
    @Override
    public ResultInfo login(String phone, String code) {
        //比较验证码是否正确
        //1-1取出redis
        String codeFromRedis  = (String) redisTemplate.opsForValue().get("code:" + phone);
        //1-2比较验证码
        if (!StrUtil.equals(code,codeFromRedis)){
            //throw new ClassCastException("验证码不正确");
            return ResultInfo.error("验证码不正确");
        }
        //根据手机查询数据库
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
        if (user == null){ //新用户
           //帮他注册
            user = new User();
            user.setPhone(phone);//绑定手机号
            user.setStatus(1);//状态设置为正常
            userMapper.insert(user); //添加用户
        }else { //老用户
            //检查状态
            if (user.getStatus()!=1){
                return ResultInfo.error("此用户已冻结,请联系企业");
            }

        }
        //jwt制作token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("phone",user.getPhone());
        String token = JwtUtil.createToken(claims);
        //将user存入redis 设置只要不超过一天登录就可以长期使用
        redisTemplate.opsForValue().set("phone:"+user.getPhone(),user,Duration.ofDays(1));
        //清除redis中的验证码
        redisTemplate.delete("code:"+code); //phone
        //8.token
        return ResultInfo.success(token);
    }

   /* //退出登录
    @Override
    public void logout(User user) {
      //清理账号
        userMapper.
    }*/
}
